package org.autumn.core.util.xml;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;

public class DomParserUtil {

	
	  public static Document getXMLDocument(String filepath) throws Exception {
	    Document doc = null;
	    try{
	      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
	      DocumentBuilder builder = dbf.newDocumentBuilder();
	      doc = builder.parse(new File(filepath));
	    } catch(ParserConfigurationException e){
	      throw new Exception(e.getMessage());
	    } catch(SAXException e){
	      throw new Exception(e.getMessage());
	    } catch(IOException e){
	      throw new Exception(e.getMessage());
	    }
	    return doc;
	  }
	  
	  public static void saveXmlFile(Document doc, String filepath) throws Exception {
	    try{
	      TransformerFactory ttf = TransformerFactory.newInstance();
	      Transformer tf = ttf.newTransformer();
	      DOMSource src = new DOMSource();
	      src.setNode(doc);
	      StreamResult target = new StreamResult();
	      target.setOutputStream(new FileOutputStream(filepath));
	      tf.setOutputProperty("indent", "yes");
	      tf.transform(src, target);
	    } catch(TransformerConfigurationException e){
	      throw new Exception(e.getMessage());
	    } catch(FileNotFoundException e){
	      throw new Exception(e.getMessage());
	    } catch(TransformerException e){
	      throw new Exception(e.getMessage());
	    }
	  }

	  public static void saveXmlFile(Document doc) {
	    throw new UnsupportedOperationException("Not yet implemented");
	  }
}
